const express = require('express')
const fs =require('fs')
const serveStatic = require('serve-static')
const { default: SseStream } = require('ssestream')

const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 先定义所有路由
app.get('/sse', (req, res) => {
  console.log('new connection')
  console.log('URL:', req.url)
  console.log('Headers:', JSON.stringify(req.headers, null, 2))
  res.setHeader(  'Content-Type', 'application/octet-stream' );
  const sseStream = new SseStream(req)
  sseStream.pipe(res)
  const pusher = setInterval(() => {
    sseStream.write({
      event: 'server-time',
      data: new Date().toTimeString()
    })
  }, 2000)
  res.on('close', () => {
    console.log('lost connection')
    clearInterval(pusher)
    sseStream.unpipe(res)
  })
})

// POST 接口用于 SSE
app.post('/sse-post', (req, res) => {
  console.log('new POST connection')
  console.log('URL:', req.url)
  console.log('Body:', JSON.stringify(req.body, null, 2))
  console.log('Headers:', JSON.stringify(req.headers, null, 2))

  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache')
  res.setHeader('Connection', 'keep-alive')
  res.setHeader('Access-Control-Allow-Origin', '*')

  const sseStream = new SseStream(req)
  sseStream.pipe(res)

  // 立即发送接收到的 POST 数据
  if (req.body) {
    sseStream.write({
      event: 'post-data',
      data: JSON.stringify({
        message: '收到 POST 数据',
        receivedData: req.body,
        timestamp: new Date().toISOString()
      })
    })
  }

  // 定期推送消息
  const pusher = setInterval(() => {
    sseStream.write({
      event: 'server-time',
      data: JSON.stringify({
        time: new Date().toTimeString(),
        timestamp: new Date().toISOString()
      })
    })
  }, 2000)

  res.on('close', () => {
    console.log('POST connection closed')
    clearInterval(pusher)
    sseStream.unpipe(res)
  })
})

// 静态文件服务放在路由之后，避免拦截 API 请求
app.use(serveStatic(__dirname))

const PORT = process.env.PORT || 9000
app.listen(PORT, '0.0.0.0', (err) => {
  if (err) throw err
  console.log(`server ready on http://0.0.0.0:${PORT}`)
})